package com.xjd.edu.utils;

import cn.hutool.core.util.IdUtil;
import com.xjd.edu.constant.SecurityConstants;
import com.xjd.edu.constant.TokenConstants;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.StringUtils;

import java.util.Optional;

import static com.xjd.edu.config.AppConfig.X_LOGIN_TOKEN;
import static com.xjd.edu.config.AppConfig.X_REQUEST_ID;


/**
 * @author wangyu
 * @since 2023/1/13
 */
public class WebHelper {

    public static String getRequestId(ServerHttpRequest request) {
        return Optional.ofNullable(request.getHeaders().getFirst(X_REQUEST_ID))
                .filter(StringUtils::hasText)
                .orElse(String.format("route_%s", IdUtil.fastSimpleUUID()));
    }

    public static String getLoginToken(ServerHttpRequest request) {
        return Optional.ofNullable(request.getHeaders().getFirst(X_LOGIN_TOKEN))
                .filter(StringUtils::hasText)
                .orElse(request.getQueryParams().getFirst(X_LOGIN_TOKEN));
    }

    /**
     * 获取请求token - ruoyi
     */
    public static String getToken(ServerHttpRequest request) {
        // 从请求头或查询参数中获取 Token
        String token = Optional.ofNullable(request.getHeaders().getFirst(SecurityConstants.AUTHORIZATION_HEADER))
                .filter(StringUtils::hasText)
                .orElse(request.getQueryParams().getFirst(SecurityConstants.AUTHORIZATION_HEADER));

        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.hasText(token) && token.startsWith(TokenConstants.PREFIX)) {
            token = token.replaceFirst(TokenConstants.PREFIX, "");
        }

        return token;
    }


}
